<template>
    <div class="game-box" ref="boxRef">
        <div class="center-card">
            <img ref="cardImgRef" class="card-img" src="@/assets/image/poke-back.png" />
            <img ref="cardImgRef" class="card-img" src="@/assets/image/poke-back.png" />
        </div>
        <div class="game-content" ref="desckRef">
            <div class="game-content-top">
                <div class="left">
                    <div class="user-item" v-for="(item) in userObj.left">
                        <UserAvatar :ref="(v) => setBoxCardList(v, item.id)" :username="item.username"
                            :totalNumber="100" :isZ="item.id === gameInfo.zjId" :isNow="item.sort === currentUserSort"
                            avatar="src/assets/image/avatar.png" :showCard="showCard.all" />
                    </div>
                </div>
                <div class="center">
                    <div class="center-bottom">
                        <div class="time">{{ time }}</div>
                    </div>
                </div>
                <div class="right">
                    <div class="user-item" v-for="(item) in userObj.right">
                        <UserAvatar :ref="(v) => setBoxCardList(v, item.id)" :username="item.username"
                            :totalNumber="100" :isRight="true" :isZ="item.id === gameInfo.zjId"
                            :isNow="item.sort === currentUserSort" avatar="src/assets/image/avatar.png"
                            :showCard="showCard.all" />
                    </div>
                </div>
            </div>
            <div class="game-content-bottom">
                <UserAvatar :ref="(v) => setBoxCardList(v, userId)" :username="'纳尔森'" :totalNumber="100"
                    :isNow="userObj.bottom.sort === currentUserSort" :isZ="userId === gameInfo.zjId"
                    avatar="src/assets/image/avatar.png" :showCard="showCard.now" />
                <var-button type="success" size="large" @click="hanCompare">比牌</var-button>
                <var-counter :min="1" :max="5" v-model="addChipNumber"/>
                <var-button type="info" size="large" @click="hanCompare">下注</var-button>
                <var-button type="danger" size="large" @click="hanCompare">弃牌</var-button>
                <!-- <var-space direction="column" align="center">
                    <var-switch v-model="isZdAddChip" />
                    <span>是否自动跟注</span>
                </var-space> -->
            </div>
        </div>
        <CompareCard ref="compareCardRef"/>
    </div>
</template>

<script setup>

import Card from '@/components/Card.vue'
import { pokeIconList, pokeNumberList } from '@/constants/enum.js'
import { useScreenOrientation, useElementBounding, defaultDocument } from '@vueuse/core'
import { useFullscreen } from '@vueuse/core'
import { computed, nextTick, onMounted, ref, toRaw } from 'vue'
import User from '@/components/User.vue';
import Opreation from '@/components/Opreation.vue';
import UserAvatar from '@/components/UserAvatar.vue'
import Chip from '@/components/Chip.vue'
import { useInterval } from '@vueuse/core'
import { gsap } from 'gsap'
import CompareCard from '@/components/CompareCard.vue'

const boxRef = ref(null);
const desckRef = ref(null);
const { x, y, top, right, bottom, left, width, height } = useElementBounding(desckRef)
const userList = ref([
    {
        id: '1',
        username: '玩家1名字测试',
        isBlind: true,
        sort: 0
    },
    {
        id: '2',
        username: '玩家2',
        isBlind: true,
        sort: 1
    },
    {
        id: '3',
        username: '玩家3',
        isBlind: true,
        sort: 2
    },
    {
        id: '4',
        username: 'John',
        isBlind: true,
        sort: 3
    },
    {
        id: '5',
        username: 'John',
        isBlind: true,
        sort: 4
    },
    {
        id: '6',
        username: 'John',
        isBlind: true,
        sort:5
    },
    {
        id: '7',
        username: 'John',
        isBlind: true,
        sort:6
    },
    {
        id: '8',
        username: 'John',
        isBlind: true,
        sort:7
    },
]);
const userId = '4'
const currentUserId = ref('1');
const currentUserSort = ref(0);
const gameInfo = ref({
    zjId: '2',
})
const time = ref(5);
const { reset, pause, resume } = useInterval(1000, {
    controls: true,
    callback: () => {
        time.value--;
        if (userList.value.length < 3) {
            userList.value.push({
                id: userList.value.length,
                username: '玩家' + (userList.value.length + 1),
                isBlind: true,
                sort: userList.value.length
            },)
        }
        if (time.value <= 0) {
            currentUserSort.value++;
            if (currentUserSort.value > userList.value.length - 1) {
                currentUserSort.value = 0;
            }
            time.value = 5;
        }
    }
})

const showCard = ref({
    all:false,
    now:false,
})

const userObj = computed(() => {
    const obj = {
        bottom: {}, // 当前用户信息
        top: [],
        left: [],
        right: []
    };
    const allUser = userList.value;
    // 找到当前用户在列表中的索引
    const currentUserIndex = allUser.findIndex(item => item.id === userId);
    // 将当前用户信息设置为bottom
    obj.bottom = allUser[currentUserIndex];

    const totalUsers = allUser.length;
    const beforeSort = ['right',
        'left'];
    const afterSort = ['left',
        'right'];
    const directions = beforeSort.length;
    // // 计算每个方向的用户数量
    const usersPerSide = Math.ceil(totalUsers / directions);
    const beforeUser = allUser.slice(0, currentUserIndex);
    const afterUser = allUser.slice(currentUserIndex + 1);
    // 将用户分配到各个方向
    beforeSort.forEach((direction, index) => {
        obj[direction] = beforeUser.slice((index) * usersPerSide, (index + 1) * usersPerSide);
    })
    afterSort.forEach((direction, index) => {
        obj[direction] = obj[direction].concat(afterUser.slice(index * usersPerSide, (index + 1) * usersPerSide));
    })
    obj.left.sort((a, b) => b.sort - a.sort)
    const lengthGap = Math.abs(obj.left.length - obj.right.length);
    if(lengthGap > 1){
        const changeNumber = Math.trunc(lengthGap / 2);
        if(obj.left.length > obj.right.length){
            const beforeItems = obj.left.splice(0,changeNumber);
            obj.right = obj.right.concat(beforeItems)
        }
    }
    const newSort = obj.right.reduce((result, item, index) => {
        if (index < currentUserIndex) {
            result.before.push(item)
        } else {
            result.after.push(item)
        }
        return result
    }, { before: [], after: [] })
    console.log(newSort)
    obj.right = newSort.after.concat(newSort.before)
    return obj;
})
const boxCardList = {};
const setBoxCardList = (ref, id) => {
    boxCardList[id] = ref;
}
const cardImgRef = ref(null);
//开始发牌
const startAnimation = () => {
    // 创建时间线
    const timeline = gsap.timeline({ paused: true });
    for (let i = 0; i < 3; i++) {
        Object.entries(boxCardList).forEach(([key, value]) => {
            const targetLeft = value.getPos().left ;
            const targetTop = value.getPos().top;
            const currentRect = cardImgRef.value.getBoundingClientRect();
            // 从当前位置偏移到中心位置
            timeline.to(cardImgRef.value, {
                duration: 0.4,
                x: targetLeft - currentRect.left,
                y: targetTop - currentRect.top,
                ease: 'power1.inOut',
                opacity: 1,
                stopOpacity: 0,
                onComplete: () => {
                    value.addCard()
                }
            });
            // // 从中心位置偏移到目标位置
            timeline.to(cardImgRef.value, {
                duration: 0,
                x: '0%',
                y: '0%',
                ease: 'power1.inOut',
            }, '+=0'); // 在前一个动画完成后0秒开始
        })
    }

    timeline.play(); // 启动时间线
}

const compareCardRef = ref(null);
const hanCompare = () =>{
    compareCardRef.value.compare()
}
//下注筹码
const addChipNumber = ref(1);
//是否自动跟注
const isZdAddChip = ref(false);
onMounted(() => {
    startAnimation();
})

document.addEventListener('DOMContentLoaded', function () {
    function resize() {
        console.log('Resizing...');
        const body = document.getElementsByTagName('body')[0];
        const html = document.getElementsByTagName('html')[0];
        const width = html.clientWidth;
        const height = html.clientHeight;
        const max = Math.max(width, height);
        const min = Math.min(width, height);
        body.style.width = `${max}px`;
        body.style.height = `${min}px`;
    }

    // 绑定 resize 事件监听器
    window.addEventListener('resize', resize);

    // 页面加载完成后立即调用一次 resize
    resize();
});
</script>

<style scoped lang="less">
.game-box {
    width: 100%;
    height: 100%;
    background: url('@/assets/image/bg-game.jpg') no-repeat center center;
    background-size: cover;
    position: relative;
    user-select: none;
    overflow: hidden;
    display: flex;

    .center-card {
        width: 80px;
        height: 80px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);

        .card-img {
            position: absolute;
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }

    .game-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 20px;
        gap: 20px;
        overflow: hidden;

        .player {
            position: absolute;
        }

        .game-content-top {
            width: 100%;
            flex: 4;
            display: flex;

            .left,
            .right {
                width: 20%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                // gap: 5px;
                .user-item {
                    margin: auto 0;
                    width: 100%;
                    flex: 1;
                    display: flex;
                    justify-content: center;
                }
            }

            .center {
                flex: 1;
                display: flex;
                flex-direction: column;

                // .center-top {
                //     height: 20%;
                //     display: flex;
                //     align-items: center;
                //     justify-content: space-evenly;
                // }

                .center-bottom {
                    flex: 1;
                    position: relative;

                    .time {
                        position: absolute;
                        top: 2%;
                        left: 50%;
                        transform: translateX(-50%);
                        padding: 10px;
                        color: #fff;
                        border-radius: 50%;
                    }
                }
            }
        }

        .game-content-bottom {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
        }
    }
}
</style>
<style lang="less">
    // @media screen and (orientation: portrait) {
    //     body{
    //         transform-origin: 0 0;
    //         transform: rotateZ(90deg) translateY(-100%);
    //     }
    // }
</style>